package com.cloudz.iptv.player;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cloudz.iptv.App;
import com.cloudz.iptv.R;
import com.cloudz.iptv.activity.BaseActivity;
import com.cloudz.iptv.fragment.content.v1.adapter.data.ItemLiveChannel;
import com.cloudz.iptv.player.base.DataInter;
import com.cloudz.iptv.player.base.ReceiverGroupManager;
import com.cloudz.iptv.utils.NetWorkSpeedUtils;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.player.IPlayer;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;
import com.kk.taurus.playerbase.widget.BaseVideoView;

import java.util.List;

import butterknife.BindView;

public class PlayerLiveActivity extends BaseActivity
{


    @BindView(R.id.video_player)
    BaseVideoView videoView;

    /**
     * 当前选中url
     */
    private String currentUrl;

    private List<ItemLiveChannel> liveChannels;

    private int position;

    private int itemCount;

    private RelativeLayout channelPlane;

    private TextView channelNum;

    private TextView channelName;

    private ImageView ad;

    @BindView(R.id.netWorkSpeed)
    TextView netWorkSpeed;

    private ReceiverGroup mReceiverGroup;

    // 是否开始
    private boolean hasStart;

    Handler handler;

    @Override
    public int getLayoutId()
    {
        return R.layout.activity_simple_play;
    }

    private Handler mHnadler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 100:
                    int ws = msg.arg1;
                    if (ws > 10 && ws <= 100)
                    {
                        netWorkSpeed.setVisibility(View.VISIBLE);
                    } else
                    {
                        netWorkSpeed.setVisibility(View.GONE);
                    }
                    netWorkSpeed.setText("当前网速： " + msg.obj.toString());
                    break;
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        new NetWorkSpeedUtils(this, mHnadler).startShowNetSpeed();

        //隐藏bar
        if (getSupportActionBar() != null)
        {
            getSupportActionBar().hide();
        }

        this.handler = new Handler();

        channelPlane = findViewById(R.id.channelPlane);

        channelNum = findViewById(R.id.channelNum);

        channelName = findViewById(R.id.channelName);

        ad = findViewById(R.id.ad);
        ad.setScaleType(ImageView.ScaleType.CENTER_CROP);

        Glide.with(App.get()).load("http://www.xanahotelle.com/upload_img/2016/04/12/20160412_160642_0000002.jpg").into(ad);

        Intent intent = getIntent();
        // 获取播放地址
        currentUrl = intent.getStringExtra("url");


        this.liveChannels = (List<ItemLiveChannel>) intent.getExtras().getSerializable("adapter");

        this.itemCount = liveChannels.size();

        this.position = intent.getIntExtra("position", 0);

        channelNum.setText(intent.getStringExtra("no"));

        channelName.setText(intent.getStringExtra("title"));

        show();

        initPlayer();

        replay();


    }

    /**
     * 重播
     */
    private void replay()
    {
        videoView.stop();

        DataSource dataSource = new DataSource(currentUrl);

        videoView.setDataSource(dataSource);

        videoView.start();
    }

    public void initPlayer()
    {

        if (!hasStart)
        {

            // 组装组件
            mReceiverGroup = ReceiverGroupManager.get().getReceiverGroup(this);


            mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_TOP_ENABLE, true);

            videoView.setReceiverGroup(mReceiverGroup);


            this.hasStart = true;
        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {

            case KeyEvent.KEYCODE_DPAD_DOWN:   //向下键

                /*    实际开发中有时候会触发两次，所以要判断一下按下时触发 ，松开按键时不触发
                 *    exp:KeyEvent.ACTION_UP
                 */
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                {

                    if (position > 0 && position < itemCount)
                    {

                        --position;

                        ItemLiveChannel itemLiveChannel = liveChannels.get(position);

                        channelNum.setText(itemLiveChannel.no);
                        channelName.setText(itemLiveChannel.title);

                        currentUrl = itemLiveChannel.url;

                        videoView.stop();

                        show();
                    }

                }

                break;

            case KeyEvent.KEYCODE_DPAD_UP:   //向上键
                if (position >= 0 && position < itemCount)
                {

                    if (position < itemCount - 1)
                    {
                        position++;
                    } else
                    {
                        break;
                    }

                    ItemLiveChannel itemLiveChannel = liveChannels.get(position);


                    channelNum.setText(itemLiveChannel.no);
                    channelName.setText(itemLiveChannel.title);

                    currentUrl = itemLiveChannel.url;

                    videoView.stop();

                    show();
                }

                break;
        }

        return super.onKeyDown(keyCode, event);
    }



    public void show()
    {
        channelPlane.setVisibility(View.VISIBLE);

        handler.removeCallbacksAndMessages(null);

        handler.postDelayed(()->{

            replay();

        }, 800);

        handler.postDelayed(()->{

            channelPlane.setVisibility(View.GONE);

        }, 3000);

    }

    @Override
    public void onPause()
    {
        super.onPause();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
        if (videoView.isInPlaybackState())
        {
            videoView.pause();
        } else
        {
            videoView.stop();
        }

    }

    @Override
    public void onResume()
    {
        super.onResume();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
        if (videoView.isInPlaybackState())
        {
            videoView.resume();
        } else
        {
            videoView.rePlay(0);
        }
        initPlayer();

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        videoView.stopPlayback();
    }
}
